package com.xiguthings.waka.web.controller.page;

import com.xiguthings.waka.dao.ModuleCode;
import com.xiguthings.waka.po.*;
import com.xiguthings.waka.po.extpo.GrowthExt;
import com.xiguthings.waka.po.extpo.PaperExt;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.cdcard.ICoolDownCardService;
import com.xiguthings.waka.service.growth.IGrowthService;
import com.xiguthings.waka.service.option.IQuestionOptionService;
import com.xiguthings.waka.service.paper.IPaperService;
import com.xiguthings.waka.service.papercard.IPaperCardService;
import com.xiguthings.waka.service.question.IPaperQuestionService;
import com.xiguthings.waka.service.sysconfig.ISysConfigService;
import com.xiguthings.waka.service.sysfile.ISysFileService;
import com.xiguthings.waka.service.task.ITaskService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.paper.PaperVo;
import com.xiguthings.waka.web.controller.question.PaperQuestionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@ApiIgnore
@Controller
@RequestMapping("/page")
public class CgiController extends AbstractController {
    @Value("${waka_server.ip_port}")
    private String wakaServerIP;


    @Resource
    private IGrowthService growthService;
    @Resource
    private IPaperService paperService;
    @Resource
    private IPaperCardService paperCardService;
    @Resource
    private IPaperQuestionService paperQuestionService;
    @Resource
    private IQuestionOptionService questionOptionService;
    @Resource
    private ITaskService taskService;
    @Resource
    private ISysFileService sysFileService;
    @Resource
    private ICoolDownCardService coolDownCardService;
    @Resource
    private ISysConfigService sysConfigService;

    /**
     * 主页
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/index.cgi")
    public String index_jsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Maintainer maintainer = (Maintainer) super.getSession().getAttribute(SESSION_CRN_MAINTAINER);
        request.setAttribute("maintainer", maintainer);
        request.setAttribute("growthList", growthService.selectByExample(new GrowthExample()));
        request.setAttribute("fileBaseUrl", wakaServerIP);
        setResponseToOpen(response);
        return "/WEB-INF/page/index.jsp";
    }

    @RequestMapping("/growth.cgi")
    public String growth_jsp(HttpServletRequest request, HttpServletResponse response, String growthId) throws Exception {
        request.setAttribute("growthId", growthId);
        GrowthExt growthExt = growthService.selectByPrimaryKeyWithAssociated(growthId);
        List<Paper> papers = growthExt.getPaperList();
        List<Paper> paperExtList = new ArrayList<>();
        for (Paper paper : papers) {
            // 找卡
            PaperCard paperCard = paperCardService.selectByPrimaryKey(paper.getPaperCardId());
            PaperTaskExample paperTaskExample = new PaperTaskExample();
            paperTaskExample.createCriteria().andPaperIdEqualTo(paper.getPaperId());
            // 找task
            List<PaperTask> paperTasks = taskService.selectByExample(paperTaskExample);
            PaperTask paperTask = null;
            if (paperTasks != null && paperTasks.size() > 0) {
                paperTask = paperTasks.get(0);
            }
            PaperExt paperExt = new PaperExt();
            BeanUtils.copyProperties(paper, paperExt);
            paperExt.setPaperCard(paperCard);
            paperExt.setPaperTask(paperTask);
            paperExtList.add(paperExt);
        }
        growthExt.setPaperList(paperExtList);
        request.setAttribute("growth", growthExt);
        setResponseToOpen(response);
        return "/WEB-INF/page/growth/growth.jsp";
    }

    @RequestMapping("/paper/paper.cgi")
    public String editPaper_jsp(HttpServletRequest request, HttpServletResponse response, String paperId) throws Exception {
        request.setAttribute("paperId", paperId);
        if (StringUtils.isNotBlank(paperId)) {
            request.setAttribute("paper", paperService.selectByPrimaryKey(paperId));
            // 加载试题
            // 加载试题以及选项
            PaperQuestionExample questionExample = new PaperQuestionExample();
            questionExample.createCriteria().andPaperIdEqualTo(paperId);
            List<PaperQuestion> questionList = paperQuestionService.selectByExample(questionExample);
            List<PaperQuestionVo> questionVoList = new ArrayList<>();
            if (questionList != null && questionList.size() > 0) {
                for (PaperQuestion question : questionList) {
                    PaperQuestionVo vo = new PaperQuestionVo();
                    vo.setPaperQuestion(question);
                    QuestionOptionExample optionExample = new QuestionOptionExample();
                    optionExample.createCriteria().andQuestionIdEqualTo(question.getQuestionId());
                    List<QuestionOption> optionList = questionOptionService.selectByExample(optionExample);
                    vo.setOptionList(optionList);
                    questionVoList.add(vo);
                }
                request.setAttribute("questionList", questionVoList);
            }
        }
        setResponseToOpen(response);
        return "/WEB-INF/page/paper/paper.jsp";
    }

    /**
     * 编辑试卷页面
     *
     * @param request
     * @param response
     * @param paperId
     * @return
     * @throws Exception
     */
    @RequestMapping("/paper/editPaper.cgi")
    public String editPaper_cgi(HttpServletRequest request, HttpServletResponse response, String paperId) throws Exception {
        if (StringUtils.isNotBlank(paperId)) {
            Paper paper = paperService.selectByPrimaryKey(paperId);
            request.setAttribute("paper", paper);
        }
        List<Growth> growthList = growthService.selectByExample(new GrowthExample());
        request.setAttribute("growthList", growthList);
        setResponseToOpen(response);
        return "/WEB-INF/page/paper/editPaper.jsp";
    }

    /**
     * 编辑试题页面
     *
     * @param request
     * @param response
     * @param questionId
     * @return
     * @throws Exception
     */
    @RequestMapping("/paper/editQuestion.cgi")
    public String editQuestion_jsp(HttpServletRequest request, HttpServletResponse response, String questionId, String paperId) throws Exception {
        PaperQuestion question = null;
        if (StringUtils.isNotBlank(questionId)) {
            question = paperQuestionService.selectByPrimaryKey(questionId);

        } else {
            question = new PaperQuestion();
            question.setPaperId(paperId);
        }
        request.setAttribute("question", question);
        setResponseToOpen(response);
        return "/WEB-INF/page/paper/editQuestion.jsp";
    }

    /**
     * 编辑答案选项页面
     *
     * @param request
     * @param response
     * @param optionId
     * @return
     * @throws Exception
     */
    @RequestMapping("/paper/editOption.cgi")
    public String editOption_jsp(HttpServletRequest request, HttpServletResponse response, String optionId, String questionId) throws Exception {
        QuestionOption option = null;
        if (StringUtils.isNotBlank(optionId)) {
            option = questionOptionService.selectByPrimaryKey(optionId);
        }
        if (StringUtils.isNotBlank(questionId)) {
            option = new QuestionOption();
            option.setQuestionId(questionId);
        }
        request.setAttribute("option", option);
        setResponseToOpen(response);
        return "/WEB-INF/page/paper/editOption.jsp";
    }

    /**
     * 查看papercard详情
     *
     * @param request
     * @param response
     * @param paperCardId
     * @return
     * @throws Exception
     */
    @RequestMapping("/paperCard/paperCard.cgi")
    public String paperCard_jsp(HttpServletRequest request, HttpServletResponse response, String paperCardId) throws Exception {
        if (StringUtils.isNotBlank(paperCardId)) {
            PaperCard paperCard = paperCardService.selectByPrimaryKey(paperCardId);
            request.setAttribute("paperCard", paperCard);
            // 获取正面图片
            SysFileExample fileExampleFront = new SysFileExample();
            fileExampleFront.createCriteria().andRelationIdEqualTo(paperCardId).andModuleCodeEqualTo(ModuleCode.CARD_FRONT);
            List<SysFile> frontFiles = sysFileService.selectByExample(fileExampleFront);
            if (frontFiles != null && frontFiles.size() > 0) {
                request.setAttribute("frontFile", frontFiles.get(0));
            }
            // 获取正面小图
            SysFileExample fileExampleFrontTH = new SysFileExample();
            fileExampleFrontTH.createCriteria().andRelationIdEqualTo(paperCardId).andModuleCodeEqualTo(ModuleCode.CARD_FRONT_TH);
            List<SysFile> frontFileThs = sysFileService.selectByExample(fileExampleFrontTH);
            if (frontFileThs != null && frontFileThs.size() > 0) {
                request.setAttribute("frontFileTH", frontFileThs.get(0));
            }
            // 反面
            SysFileExample fileExampleBack = new SysFileExample();
            fileExampleBack.createCriteria().andRelationIdEqualTo(paperCardId).andModuleCodeEqualTo(ModuleCode.CARD_BACK);
            List<SysFile> backFiles = sysFileService.selectByExample(fileExampleBack);
            if (backFiles != null && backFiles.size() > 0) {
                request.setAttribute("backFile", backFiles.get(0));
            }
            // 反面小图
            SysFileExample fileExampleBackTH = new SysFileExample();
            fileExampleBackTH.createCriteria().andRelationIdEqualTo(paperCardId).andModuleCodeEqualTo(ModuleCode.CARD_BACK_TH);
            List<SysFile> backFileTHs = sysFileService.selectByExample(fileExampleBackTH);
            if (backFileTHs != null && backFileTHs.size() > 0) {
                request.setAttribute("backFileTH", backFileTHs.get(0));
            }
        }
        request.setAttribute("fileBaseUrl", wakaServerIP);
        setResponseToOpen(response);
        return "/WEB-INF/page/paperCard/paperCard.jsp";
    }

    /**
     * 编辑paperCard页面
     *
     * @param request
     * @param response
     * @param paperCardId
     * @return
     * @throws Exception
     */
    @RequestMapping("/paperCard/editPaperCard.cgi")
    public String editPaperCard_jsp(HttpServletRequest request, HttpServletResponse response, String paperCardId, String paperId) throws Exception {
        request.setAttribute("paperCardId", paperCardId);
        request.setAttribute("paperId", paperId);
        if (StringUtils.isNotBlank(paperCardId)) {
            PaperCard paperCard = paperCardService.selectByPrimaryKey(paperCardId);
            request.setAttribute("paperCard", paperCard);
        }
        setResponseToOpen(response);
        return "/WEB-INF/page/paperCard/editPaperCard.jsp";
    }

    @RequestMapping("/task/editTask.cgi")
    public String task_jsp(HttpServletRequest request, HttpServletResponse response, String paperTaskId, String paperId) throws Exception {
        request.setAttribute("paperTaskId", paperTaskId);
        request.setAttribute("paperId", paperId);
        if (StringUtils.isNotBlank(paperTaskId)) {
            PaperTask task = taskService.selectByPrimaryKey(paperTaskId);
            request.setAttribute("paperTask", task);
        }
        setResponseToOpen(response);
        return "/WEB-INF/page/task/editTask.jsp";
    }

    @RequestMapping("/banner/banner.cgi")
    public String banner_jsp(HttpServletRequest request, HttpServletResponse response, Integer status) throws Exception {
        request.setAttribute("status", status);
        SysFileExample fileExample = new SysFileExample();
        SysFileExample.Criteria criteria = fileExample.createCriteria();
        criteria.andRelationIdEqualTo(ModuleCode.BANNER).andModuleCodeEqualTo(ModuleCode.BANNER);
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        List<SysFile> sysFiles = sysFileService.selectByExample(fileExample);

        request.setAttribute("banners", sysFiles);
        request.setAttribute("fileBaseUrl", wakaServerIP);
        setResponseToOpen(response);
        return "/WEB-INF/page/banner/banner.jsp";
    }

    @RequestMapping("/cdcard/cdcard.cgi")
    public String cdcard_jsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<CoolDownCard> coolDownCards = coolDownCardService.selectByExample(new CoolDownCardExample());
        List<SysFile> sysFiles = new ArrayList<>();
        for (CoolDownCard coolDownCard : coolDownCards) {
            SysFileExample fileExample = new SysFileExample();
            SysFileExample.Criteria criteria = fileExample.createCriteria();
            criteria.andRelationIdEqualTo(coolDownCard.getCoolDownCardId()).andModuleCodeEqualTo(ModuleCode.BG_IMG);
            List<SysFile> sysFilesDB = sysFileService.selectByExample(fileExample);
            if (sysFilesDB != null && sysFilesDB.size() > 0) {
                sysFiles.add(sysFilesDB.get(0));
            } else {
                sysFiles.add(new SysFile());
            }
        }
        request.setAttribute("cdCardFiles", sysFiles);
        request.setAttribute("cdCardList", coolDownCards);
        request.setAttribute("fileBaseUrl", wakaServerIP);
        setResponseToOpen(response);

        return "/WEB-INF/page/cdcard/cdcard.jsp";
    }

    @RequestMapping("/sysconfig/sysconfig.cgi")
    public String sysconfig_jsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<SysConfig> sysConfigs = sysConfigService.selectByExample(new SysConfigExample());
        request.setAttribute("sysConfigList", sysConfigs);
        setResponseToOpen(response);
        return "/WEB-INF/page/sysconfig/sysconfig.jsp";
    }


    //====================================================

    /**
     * 查看所有卡片页面
     *
     * @param request
     * @param response
     * @param growthId
     * @return
     * @throws Exception
     */
    @RequestMapping("/card/card.cgi")
    public String card_jsp(HttpServletRequest request, HttpServletResponse response, String growthId) throws Exception {
        GrowthExample growthExample = new GrowthExample();
        GrowthExample.Criteria criteria = growthExample.createCriteria();
        criteria.andStatusNotEqualTo(99);
        growthExample.setOrderByClause("rank");
        List<Growth> list = growthService.selectByExample(growthExample);
        if (list != null && list.size() > 0) {
            PaperExample paperExample = new PaperExample();
            paperExample.setOrderByClause("rank");
            if (StringUtils.isNotBlank(growthId)) {
                paperExample.createCriteria().andGrowthIdEqualTo(growthId);
            } else {
                paperExample.createCriteria().andGrowthIdEqualTo(list.get(0).getGrowthId());
            }
            List<Paper> paperList = paperService.selectByExample(paperExample);
            if (paperList != null && paperList.size() > 0) {
                List<PaperVo> paperVoList = new ArrayList<>(paperList.size());
                for (Paper paper : paperList) {
                    PaperVo paperVo = new PaperVo();
                    paperVo.setPaper(paper);
                    PaperCard paperCard = paperCardService.selectByPrimaryKey(paper.getPaperCardId());
                    paperVo.setPaperCard(paperCard);
                    paperVoList.add(paperVo);
                }
                request.setAttribute("paperVoList", paperVoList);
            }
        }
        request.setAttribute("growthList", list);
        request.setAttribute("growthId", growthId);
        setResponseToOpen(response);
        return "/WEB-INF/page/card/card.jsp";
    }

    /**
     * 编辑维度页面
     *
     * @param request
     * @param growthId
     * @return
     * @throws Exception
     */
    @RequestMapping("/growth/editGrowth.cgi")
    public String editGrowth_cgi(HttpServletRequest request, String growthId,HttpServletResponse response) throws Exception {
//        request.setAttribute("referer", request.getHeader("referer"));
        if (StringUtils.isNotBlank(growthId)) {
            Growth growth = growthService.selectByPrimaryKey(growthId);
            request.setAttribute("growth", growth);
            request.setAttribute("growthId", growthId);
        }
        setResponseToOpen(response);
        return "/WEB-INF/page/growth/editGrowth.jsp";
    }

    /**
     * 编辑卡片页面
     *
     * @param request
     * @param paperId
     * @param growthId
     * @param paperCardId
     * @return
     * @throws Exception
     */
    @RequestMapping("/card/editCard.cgi")
    public String editCard_cgi(HttpServletRequest request,HttpServletResponse response, String paperId, String growthId, String paperCardId) throws Exception {
        request.setAttribute("paperId", paperId);
        request.setAttribute("growthId", growthId);
        request.setAttribute("paperCardId", paperCardId);
//        request.setAttribute("referer", request.getHeader("referer"));
        if (StringUtils.isBlank(paperCardId)) {
            if (StringUtils.isNotBlank(paperId)) {
                Paper paper = paperService.selectByPrimaryKey(paperId);
                request.setAttribute("paper", paper);
            }
            return "/WEB-INF/page/card/paper.jsp";
        }
        PaperCard paperCard = paperCardService.selectByPrimaryKey(paperCardId);
        request.setAttribute("paperCard", paperCard);
        setResponseToOpen(response);
        return "/WEB-INF/page/card/editCard.jsp";
    }


//    /**
//     * 查看试卷页面
//     *
//     * @param request
//     * @param paperId
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/card/paper.cgi")
//    public String paper_cgi(HttpServletRequest request, String paperId, String paperCardId, String growthId) throws Exception {
//        request.setAttribute("paperId", paperId);
//        request.setAttribute("paperCardId", paperCardId);
//        request.setAttribute("growthId", growthId);
////        String referer = request.getHeader("referer");
////        request.setAttribute("referer", request.getHeader("referer"));
//        if (StringUtils.isNotBlank(paperId)) {
//            Paper paper = paperService.selectByPrimaryKey(paperId);
//            request.setAttribute("paper", paper);
//            if (paper != null) {
//                // 加载task
//                PaperTaskExample taskExample = new PaperTaskExample();
//                taskExample.createCriteria().andPaperIdEqualTo(paperId);
//                List<PaperTask> paperTaskList = taskService.selectByExample(taskExample);
//                request.setAttribute("paperTaskList", paperTaskList);
//                // 加载试题以及选项
//                PaperQuestionExample questionExample = new PaperQuestionExample();
//                questionExample.createCriteria().andPaperIdEqualTo(paperId);
//                List<PaperQuestion> questionList = paperQuestionService.selectByExample(questionExample);
//                List<PaperQuestionVo> questionVoList = new ArrayList<>();
//                if (questionList != null && questionList.size() > 0) {
//                    for (PaperQuestion question : questionList) {
//                        PaperQuestionVo vo = new PaperQuestionVo();
//                        vo.setPapaerQuestion(question);
//                        QuestionOptionExample optionExample = new QuestionOptionExample();
//                        optionExample.createCriteria().andQuestionIdEqualTo(question.getQuestionId());
//                        List<QuestionOption> optionList = questionOptionService.selectByExample(optionExample);
//                        vo.setOptionList(optionList);
//                        questionVoList.add(vo);
//                    }
//                    request.setAttribute("questionList", questionVoList);
//                }
//            }
//        }
//        return "/WEB-INF/page/card/paper.jsp";
//    }

}
